﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Marmat.Template.WinForm
{

    /// <summary>
    ///单据管理器的默认浏览窗体
    /// </summary>
    /// <typeparam name="Entity"></typeparam>
    /// <typeparam name="DataSource"></typeparam>
    public partial class DocumentViewForm<Entity, DataSource> : Form, IDocumentViewForm<Entity, DataSource>
    {

        /// <summary>
        /// 构建一个单据管理器的默认浏览窗体的实例。
        /// </summary>
        public DocumentViewForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取视图控制器
        /// </summary>
        public IDocumentViewFormController<Entity, DataSource> Controller { get; set; }

        void IDocumentViewForm<Entity, DataSource>.Load(DataSource data)
        {
            this.bGridControl1.DataSource = data;
        }

        private void BGridControl1_RowCellDoubleClick(object sender, Forms.Views.Grid.RowColEventArgs e)
        {
            object id = e.GridControl.GetRowCellValue(e.RowHandle, this.Controller.Management.Command.PrimaryName);
            this.Controller.Management.ShowEditForm(id);
        }

        private void UserEntityViewForm_Load(object sender, EventArgs e)
        {
            if (this.DesignMode) return;

            IEnumerable<ColumnEntity> columnCollection = this.Controller.Management.GetColumnCollection();
            if (columnCollection is null || columnCollection.Count() == 0)
            {
                throw new Exception("视图列集合(ViewColumnCollection)不能为null或为空!");
            }
            //视图列集合
            IEnumerable<ColumnEntity> columns = columnCollection;
            ICustomBuildColumn builder = this.Controller.Management.Command as ICustomBuildColumn;
            foreach (var item in columns)
            {
                bool cancel = false;
                Forms.Views.Grid.Column column = new Forms.Views.Grid.Column();
                column.Name = item.Name;
                column.Caption = item.Caption;
                column.FieldName = item.Name;
                if (builder != null)
                {
                    BuildColumnArgs args = new BuildColumnArgs();
                    args.Column = column;
                    builder.BuildColumn(args);
                    cancel = args.Cancel;
                }
                if (cancel == false)
                    this.bGridControl1.Columns.Add(column);
            }
        }
    }
}
